package com.autohelper.app;

import static android.app.Activity.RESULT_OK;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;

public class ScreenCaptureService extends Service {
    private static final String TAG = "截屏服务";
    public static ActionOperator.IActionCallback callback;
    private MediaProjection mediaProjection;
    private ImageReader imageReader;
    private Handler handler = new Handler(Looper.getMainLooper());

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 初始化 MediaProjection 和 ImageReader
        int resultCode = ServiceHolder.INSTANCE.getScreenCaptureManager().getResultCode();
        Intent data = ServiceHolder.INSTANCE.getScreenCaptureManager().getData();
        if (resultCode == RESULT_OK && data != null) {
            startScreenCapture(data);
        } else {
            stopSelf();
        }
        return START_STICKY;
    }

    private void startScreenCapture(Intent data) {
        // 获取屏幕尺寸
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        int density = metrics.densityDpi;

        // 创建 ImageReader
        imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2);

        // 设置 ImageReader 的回调
        imageReader.setOnImageAvailableListener(reader -> {
            // 获取截屏图像
            Image image = reader.acquireLatestImage();
            if (image != null) {
                // 将图像数据保存为 Bitmap
                Bitmap bitmap = imageToBitmap(image);
//                try {
//                    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
//                    File imgFile = new File(storageDir, "test.png");
//                    FileOutputStream ou = new FileOutputStream(imgFile);
//                    bitmap.compress(Bitmap.CompressFormat.PNG, 60, ou);
//                    ou.flush();
//                    ou.close();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, out);
                if (callback != null) {
                    byte[] imgs = out.toByteArray();
                    callback.success(imgs);
                }
                // 释放 Image 对象
                image.close();
            }
            // 关闭 ImageReader 和 MediaProjection
            releaseResources();
        }, handler);

        // 初始化 MediaProjection
        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        mediaProjection = mediaProjectionManager.getMediaProjection(RESULT_OK, data);

        // 创建虚拟显示
        mediaProjection.createVirtualDisplay(
                "ScreenCapture",
                width, height, metrics.densityDpi,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                imageReader.getSurface(),
                null,
                handler
        );
    }

    private Bitmap imageToBitmap(Image image) {
        int width = image.getWidth();
        int height = image.getHeight();
        Image.Plane[] planes = image.getPlanes();
        ByteBuffer buffer = planes[0].getBuffer();
        int pixelStride = planes[0].getPixelStride(); // 每个像素的字节数
        int rowStride = planes[0].getRowStride(); // 每行的字节数
        int rowPadding = rowStride - pixelStride * width; // 每行的填充字节

        // 创建一个 Bitmap
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        long start = System.currentTimeMillis();
        // 如果 rowStride 等于 width * pixelStride，可以直接复制数据
        if (rowStride == width * pixelStride) {
            bitmap.copyPixelsFromBuffer(buffer);
        } else {
            // 如果 rowStride 大于 width * pixelStride，需要处理填充字节
            ByteBuffer packedBuffer = ByteBuffer.allocateDirect(width * height * pixelStride);
            for (int y = 0; y < height; y++) {
                buffer.position(y * rowStride); // 定位到当前行的起始位置
                int rowLength = width * pixelStride; // 每行的有效数据长度
                byte[] rowData = new byte[rowLength];
                buffer.get(rowData); // 复制当前行的有效数据
                packedBuffer.put(rowData); // 将有效数据写入 packedBuffer
            }
            packedBuffer.rewind(); // 重置缓冲区位置
            bitmap.copyPixelsFromBuffer(packedBuffer);
        }
        long end = System.currentTimeMillis();
        Log.i(TAG, "耗时=" + (end - start) + " ms");
        return bitmap;
    }

    private void releaseResources() {
        // 关闭 ImageReader
        if (imageReader != null) {
            imageReader.close();
            imageReader = null;
        }

        // 停止 MediaProjection
        if (mediaProjection != null) {
            mediaProjection.stop();
            mediaProjection = null;
        }

        // 停止 Service
        stopSelf();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}